package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {
    @Autowired
    ApArticleMapper apArticleMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;
    @Autowired
    AuthorMapper authorMapper;
    @Autowired
    Configuration configuration;
    @Resource(name ="minIOFileStorageService" )
    FileStorageService fileStorageService;
    @Override
    public void generateArticlePage(Long articleId) {
    log.info("静态页生成方法被触发=========articleId==>{}",articleId);
    //1.根据文章id查询文章信息
        ApArticle apArticle = apArticleMapper.selectById(articleId);
        if (apArticle==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, articleId));
        if (apArticleContent==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ApAuthor author = authorMapper.selectById(apArticle.getAuthorId());
        if (author==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
     //准备数据模型
        List<Map> content = JSONArray.parseArray(apArticleContent.getContent(), Map.class);
        Map params = new HashMap<>();
          params.put("authorApUserTd",author.getUserId());
          params.put("article",apArticle);
          params.put("content",content);
     //获取模板
        try {
            Template template = configuration.getTemplate("article.ftl");//已经获取到模板了
            //调用模板引擎API，替换模板内容
            StringWriter stringWriter = new StringWriter();
            template.process(params,stringWriter);
            String s = stringWriter.toString();
            InputStream inputStream = new ByteArrayInputStream(stringWriter.toString().getBytes());
            String path = fileStorageService.store("article", apArticle.getId() + ".html", "text/html", inputStream);
            apArticle.setStaticUrl(path);
            System.out.println(path);
            apArticleMapper.updateById(apArticle);
            log.info("页面静态化页面生成成功！");


        } catch (IOException | TemplateException e) {
            e.printStackTrace();
            log.info("页面静态化失败！原因{}",e.getMessage());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"页面静态化失败！原因是："+e.getMessage());
        }
    }
}
